Model Classes In Vapor

To be able to use model classes in both vapor and iOS/MacOS project, it’s best to make use of


Xcode 

conditional compile variable.


Example:


final class Tip : Codable {
  var id : Int?
  var name : String
  var description: String
  
  init(name : String, description: String) {
    self.name = name
    self.description = description
  }
}

#if Xcode
import FluentPostgreSQL
import Vapor

extension Tip : PostgreSQLModel {}
extension Tip : Content{}
extension Tip : Migration{}
extension Tip : Parameter{}
#endif

When making model object for Vapor App, aim to use classes, not structs (for numerous reasons that will be explained later).


Also, conforming to Codable gives you easy persistence.


When you conform to Vapor’s Content protocol you get easy representation of your model in an HTTP message:


public protocol Content: Codable, ResponseCodable, RequestCodable

The class first conforms to Content, and in another part of the file to Codable. That may seem redundant, but I wanted to use the same file for server and client app.


Prev: Stop / Start Docker Apps

Next: Parent - Child Relationships in Model Classes


Vapor 3 Tutorial Start


#vapor #swift #pub #tips #model